package com.jjc.android

import android.content.Context
import android.content.Intent
import com.hjq.toast.ToastUtils
import com.jjc.android.activity.LoginActivity
import com.jjc.android.entity.LzyResponse
import com.jjc.android.entity.UserInfo
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.Common
import com.jjc.android.util.defACache
import com.jjc.android.util.defSP
import com.jjc.android.util.paramEx
import com.jjc.android.view.formatTwo
import com.lzy.okgo.OkGo
import java.text.SimpleDateFormat
import java.util.*

object UserManager {

    private var userInfo: UserInfo by defACache("user_info", UserInfo())
    var isShowGuide:Boolean by defSP("is_show_guide",false)
    var isPopuAgreement:Boolean by defSP("is_popu_agreement",false)
    @JvmStatic
    fun loginSuccess(user: UserInfo){
        userInfo = user
    }

    fun userInfo(): UserInfo {
        return userInfo
    }


    @JvmStatic
    fun logout(action:()->Unit){
        OkGo.post<LzyResponse<String>>(Constants.logoutApp)
            .headers("Authorization",UserManager.userToken())
            .execute(object : SimpleHttpCallback<LzyResponse<String>>(false, isThird = true){
                override fun onCallSuccess(response: LzyResponse<String>) {
                    realLogout()
                    action.invoke()
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    realLogout()
                    action.invoke()
                }

            })

    }

    private fun realLogout(){
        userInfo = UserInfo()
    }


    @JvmStatic
    fun isLogin(): Boolean {
        return !userToken().isNullOrEmpty()
    }

    @JvmStatic
    fun toLogin(context: Context?): Boolean {
        if (!isLogin()) {
            context.let {
                LoginActivity.start((if(it==null) App.getContext() else context)!!)
            }
            return true
        }
        return false
    }

    fun applicationId():String{
        return "13aa4626c7014c1b93136c038019db8c"
    }

    fun userId():String{
        return userInfo.tuoTuUserId
    }

    @JvmStatic
    fun userToken(): String? {
        return userInfo.userToken
    }
    private val fileNameDf by lazy {
        SimpleDateFormat("yyMMddHHmmss", Locale.getDefault())
    }
    private var count = 1

    private fun fetchCount():String{
        if(count>=100){
            count = 1
        }
        val lable = count.formatTwo()
        count++
        return lable
    }

    fun fileName():String{
        return String.format("%s0%s%s", userInfo.mobile,fileNameDf.format(Date()), fetchCount())
    }

}
